(function($) {
    $(function(event) {

		var ordinals = new Array(
			'ORDINAL_FIRST'.translate(),
			'ORDINAL_SECOND'.translate(),
			'ORDINAL_THIRD'.translate(),
			'ORDINAL_FOURTH'.translate(),
			'ORDINAL_FIFTH'.translate(),
			'ORDINAL_SIXTH'.translate(),
			'ORDINAL_SEVENTH'.translate(),
			'ORDINAL_EIGHTH'.translate(),
			'ORDINAL_NINETH'.translate(),
			'ORDINAL_TENTH'.translate()
		);
		
		var firstCitiesData;
		
		var pVal = $('#tourists-number').val();
		
		var agesMass = [];
		var agesMassMax = 0;
		$('#adults-list li:first .custom-select .custom-select-body-i ul li').each(function() {
			agesMass.push($(this).find('a').metadata().value);
		});
		agesMassMax = Math.max.apply(Math, agesMass);
		function showAdvancedSearch() {
			$('.search_controls a.more').hide();
			$('.search_controls a.less').css('display', 'block');
			$('.hotel_search_more').show();
			$('#adults-list').show();
		}

		if ($('#adults > input[type="hidden"]').val() > 0 ||
			$('#babies > input[type="hidden"]').val() > 0 ||
			$('#rooms > input[type="hidden"]').val() > 1 ||
			$('#price-from').val() != '' ||
			$('#price-to').val() != '' ||
			$('#nutrition-type > input[type="hidden"]').val() != '' ||
			$('#input-hotelname').val() != '' ||
			$('#chk-onlyavail').attr('checked') == true ||
			pVal != 2 ||
			($('#price-markup').length > 0 && !$('#price-markup').is(':checked')))
		{
			showAdvancedSearch();
		}

		for (var i = 1; i <= pVal; i++) {
			var liNth = $('#adults-list li:nth-child(' + i + ')');
			if (!$('#frm-air').length > 0) {
				liNth.find('label').text(ordinals[i-1] + ' ' + 'TOURIST'.translate() + ':');
			}
			liNth.show();
			
			if (!liNth.find('input[type="hidden"]').length > 0) {
				liNth.find('.custom-select').prepend('<input class="js-added" type="hidden" name="p[]" value="0" />');
			}
			if (liNth.find('.custom-select input[type="hidden"]').val() != agesMassMax) {
				showAdvancedSearch();
			}
		}
		
		var span = $('#city-selector .custom-select-header div');
		var spanHeader = $('#city-selector .custom-select-header');
		var spanEnd = $('#city-end-selector .custom-select-header div');
		var spanEndHeader = $('#city-end-selector .custom-select-header');
		var countryValInput = $('#selector-country > input[type="hidden"]');
		var locationTr = $('#location').parents('tr');
		//var supplier = $('#selector-supplier');
		showCustomSelectVar = false;
		var citySelHeightIE = function() {
			if ($.browser.msie && $.browser.version.number < 7) {
				var csb = $('#city-selector div.custom-select-body');
				var csbh = csb.height();
				csb.css({height: 'auto'});
				if (csbh >= 443) {
					csb.css({height: '443px'});
				}
			}
		};
		citySelHeightIE();
		var hideThis = function(elm) {
			if (!$.browser.msie) {
				elm.slideUp('fast');
			} else {
				elm.hide();
			}
		};
		$(document).bind('keypress', function(event) {
			switch(event.keyCode) {
				case 27:
					$('.custom-select-header > div').removeClass('sel-active');
					hideThis($('.custom-select-body'));
					showCustomSelectVar = false;
					tm.Popup.popupClose();
					break;
			}
		});
		var countrySelectorDisable = function() {
			$('#selector-country .custom-select-header div').addClass('disabled');
			$('#selector-country .custom-select-header').unbind('mousedown', cSelectClick);
		};
		var countrySelectorEnable = function() {
			if ($('#selector-country .custom-select-header div').hasClass('disabled')) {
				$('#selector-country .custom-select-header div').removeClass('disabled');
				$('#selector-country .custom-select-header').bind('mousedown', cSelectClick);
			}
		};
		var citySelectorDisable = function() {
			span.addClass('disabled');
			spanHeader.unbind('mousedown', custSelectClick);
			spanEnd.addClass('disabled');
			spanEndHeader.unbind('mousedown', custSelectClick);
		};
		if (countryValInput.val() == '') {
			citySelectorDisable();
		}
		var citySelectorEnable = function() {
			if (span.hasClass('disabled')) {
				span.removeClass('disabled');
				spanHeader.bind('mousedown', custSelectClick);
				spanEnd.removeClass('disabled');
				spanEndHeader.bind('mousedown', custSelectClick);
			}
		};
		var citySelectorSetWait = function() {
			span.find('span').css({background: 'url(/i/free-site-wizard/ajax-loader.gif) 0 0 no-repeat', textIndent: '-999em'});
			spanEnd.find('span').css({background: 'url(/i/free-site-wizard/ajax-loader.gif) 0 0 no-repeat', textIndent: '-999em'});
		};
		var citySelectorRemoveWait = function() {
			span.find('span').css({background: 'none', textIndent: 0});
			spanEnd.find('span').css({background: 'none', textIndent: 0});
		};
		/*var supplierSelectorSetWait = function() {
			supplier.find('span').css({background: 'url(/i/free-site-wizard/ajax-loader.gif) 0 0 no-repeat', textIndent: '-999em'});
		}
		var supplierSelectorRemoveWait = function() {
			supplier.find('span').css({background: 'none', textIndent: 0});
		}
		var companySelectorDisable = function() {
			$('#selector-supplier .custom-select-header div').addClass('disabled');
			$('#selector-supplier .custom-select-header').unbind('mousedown', cSelectClick);
		}
		var companySelectorEnable = function() {
			$('#selector-supplier .custom-select-header div').removeClass('disabled');
			$('#selector-supplier .custom-select-header').bind('mousedown', cSelectClick);
		}*/
		var countriesArray = [];
		$('#selector-country .custom-select-body-i a').mousedown(function() {
			var $this = $(this);
			if (span.is(':hidden')) {
				span.next('.ct-error').remove();
				span.show();
			}
			if (locationTr.is(':visible')) {
				locationTr.hide();
			}
			$this.parents('ul').find('li.active').removeClass('active');
			$this.parent(0).addClass('active');
			$('#city-selector .custom-select-body-i').html('<table></table>');
			var temp = $('#city-selector .custom-select-header span');
			temp.text(temp.metadata().defText);
			if ($('#city-end-selector').length > 0) {
				$('#city-end-selector .custom-select-header span').text($('#city-end-selector .custom-select-header span').metadata().defText);
			}
			span.html(span.metadata().defText);
			spanEnd.html(span.metadata().defText);
			var citySelectorInp = $('#city-selector input[type="hidden"], #city-end-selector input[type="hidden"]');
			if (citySelectorInp.val() != '') {
				citySelectorInp.val('');
			}
			countryValInput.val($this.metadata().value);
			$('#selector-country .custom-select-header span').text($this.text());
			citySelectorDisable();
			citySelectorSetWait();
			countrySelectorDisable();
			bodyClickCSelectHide();
			var countryVal = countryValInput.val();
			if ($('#' + countryVal).length <= 0) {
				//$.getJSON("/a_ajax/location.getCitiesData?id=" + encodeURIComponent($('#selector-country input[type="hidden"]').val()), firstResponse);
				var nocache = '';
				if (location.href.match(/nocache=/i)) {
					nocache = '&nocache=1';
				}
				var getCitiesUrl = "/a_ajax/location.getCitiesData";
				if ($this.parents('form').is('#frm-car-search')) {
					getCitiesUrl = "/a_ajax/location.getCarCitiesData";
				}
				$.ajax({
					url: getCitiesUrl + "?id=" + encodeURIComponent(countryValInput.val()) + nocache,
					type: "GET",
					dataType : "json",
					timeout: 10000,
					success: firstResponse,
					error: firstRequestError
				});
			} else {
				citySelectorRemoveWait();
				countrySelectorEnable();
				citySetContentFromHTML();
				citySelectorEnable();
			}
			hideThis($this.parents('.custom-select-body'));
		});
		var citySetContentFromHTML = function() {
			//$('#city-selector .custom-select-body-i').html($('#' + countryValInput.val()).html());
			firstResponse(countriesArray[countryValInput.val()]);
		};
		var firstRequestError = function() {
			var nocache = '';
			if (location.href.match(/nocache=/i)) {
				nocache = '&nocache=1';
			}
			var getCitiesUrl = "/a_ajax/location.getCitiesData";
			if ($(this).parents('form').is('#frm-car-search')) {
				getCitiesUrl = "/a_ajax/location.getCarCitiesData";
			}
			$.ajax({
				url: getCitiesUrl + "?id=" + encodeURIComponent(countryValInput.val()) + nocache,
				type: "GET",
				dataType : "json",
				timeout: 10000,
				success: firstResponse,
				error: secondRequestError
			});
		};
		var secondRequestError = function() {
			$('#ajax-loader').remove();
			if (countryValInput.val() != '') {
				countrySelectorEnable();
				citySelectorRemoveWait();
			} else {
				alert('ERROR'.translate());
			}
			span.find('span').text('NO_CITY'.translate());
		};
		var custSelectClick = function(event) {
			event.preventDefault();
			event.stopPropagation();
			$('.custom-select .custom-select-header div').removeClass('sel-active');
			hideThis($('.custom-select .custom-select-body'));
			!showCustomSelectVar ? showCustomSelect(this) : hideCustomSelect(this);
		};
		spanHeader.bind('mousedown', custSelectClick);
		spanEndHeader.bind('mousedown', custSelectClick);
		var bodyClickCSelectHide = function() {
			$('body').bind('mousedown', function() {
				if ($('.custom-select-body').length > 0) {
					$('.custom-select .custom-select-header div').removeClass('sel-active');
					hideThis($('.custom-select-body').not(':hidden'));
					showCustomSelectVar = false;
				}
			});
		};
		var bodyUnbindClick = function() {
			$('body').unbind('mousedown');
		};
		$('.custom-select').mouseover(bodyUnbindClick);
		$('.custom-select').mouseout(bodyClickCSelectHide);
		
		var hideSubCities = function() {
			$('#city-selector .custom-select-body .cities-block td.hasSub').removeClass('hasSubActive');
			$('#city-selector .custom-select-body tr.subActive').hide();
		};
		var selectCityBind = function(cities) {
			$('#city-selector .custom-select-body .cities-block td').find('a').unbind('mousedown').bind('mousedown', {locations: cities}, selectCity);
			$('#city-end-selector .custom-select-body .cities-block td').find('a').unbind('mousedown').bind('mousedown', {locations: cities}, selectCity);
			$('#city-selector .custom-select-body .cities-block td.hasSub strong').unbind('mousedown').bind('mousedown', function() {
				var
					$this = $(this),
					td = $this.parents('td.hasSub'),
					num = parseInt($this.parents('td.hasSub').attr('name')),
					tr = $this.parents('tr.cities-block').nextAll('tr.subActive_' + num).eq(0)
				;
				if (td.hasClass('hasSubActive')) {
					$this.parents('table').find('td.hasSubActive').removeClass('hasSubActive');
					$this.parents('table').find('tr.subActive').hide();
					td.removeClass('hasSubActive');
					tr.hide();
				} else {
					$this.parents('table').find('td.hasSubActive').removeClass('hasSubActive');
					$this.parents('table').find('tr.subActive').hide();
					td.addClass('hasSubActive');
					tr.show();
					//$this.parents('div.custom-select-body').scrollTo($this, 800, {offset: -50});
				}
			});
		};
		/*
		var showCompany = function() {
			supplierSelectorSetWait();
			$.ajax({
				url: '/a_ajax/supplier/supplier.getSuppliers',
				type: 'GET',
				dataType: 'json',
				success: function(data) {
					companySelectorEnable();
					supplierSelectorRemoveWait();
					supplier.find('.custom-select-body-i ul').html('');
					for (var i = 0; i < data.length; i++) {
						supplier.find('.custom-select-body-i ul').append('<li class="simple-select-row"><a href="javascript:void(0)" class="{value: ' + "'" + data[i].code + "'" + '}">' + data[i].name + '</a></li>');
					}
				},
				error: function() {
					alert('ERROR'.translate());
				}
			});
		}
		*/
		var selectCity = function(arr) {
			bodyUnbindClick();
			var $this = $(this);
			if ($this.parent(0).hasClass('hasSubActive') || $this.parents('tr.subActive').length <= 0) {
				hideSubCities();
			}
			if (!$this.parents('.cities-block').hasClass('c-navigation')) {
				$this.parents('.custom-select').find('.custom-select-header span').text($this.text());
				$this.parents('.custom-select-body').find('.cities-block td.active').removeClass('active');
				$this.parent(0).addClass('active');
				hideCustomSelect(this);
				if ($this.hasClass('has_regions')) {
					for (var i = 0; i < arr.data.locations.length; i++) {
						for (var j = 0; j < arr.data.locations[i].l.length; j++) {
							$('#location .custom-select-body ul').append('<li class="simple-select-row"><a href="javascript:void(0)" class="{value: \'' + arr.data.locations[i].l + '\'}">' + arr.data.locations[i].l + '</a></li>');
						}
					}
					locationTr.show();
				}
				/*if ($this.parents('form').is('#frm-car-search')) {
					showCompany();
				}*/
			}
			$this.parents('.custom-select').find('input[type="hidden"]').val($this.attr('name'));
			if ($('#city-end-selector').length > 0 && $this.parents('.custom-select').attr('id') == 'city-selector' && $('#city-end-selector .custom-select-header span').text() == $('#city-end-selector .custom-select-header span').metadata().defText) {
				$('#city-end-selector .custom-select-header span').text($this.text());
				$('#city-end-selector input[name="ect"]').val($this.attr('name'));
				$('#city-end-selector .ul td').removeClass('active');
				$('#city-end-selector .ul a[name="' + $this.attr('name') + '"]').parent(0).addClass('active');
			}
		};
		var scrollBody = function(elm) {
			var b = elm.parents('.custom-select').find('.custom-select-body'),
				a = b.find('.active');
			if (a.length > 0) {
				b.scrollTo(a, 100, {queue:true, offset:-80});
			}
		};
		var showCustomSelect = function(elm) {
			showCustomSelectVar = true;
			if (countryValInput.val() != '') {
				if ($(elm).parents('.custom-select').find('.custom-select-body-i').children().size() == 0) {
					$('#city-selector .custom-select-body-i').append('<img id="ajax-loader" src="/i/ajax-loader-white.gif" width="42" height="42" alt="' + 'LBL_LOADING'.translate() + '" />');
					if ($('#city-end-selector').length > 0) {
						$('#city-end-selector .custom-select-body-i').append('<img id="ajax-loader" src="/i/ajax-loader-white.gif" width="42" height="42" alt="' + 'LBL_LOADING'.translate() + '" />');
					}
					setTimeout(function() {
						//$.getJSON("/a_ajax/location.getCitiesData?id=" + $('#selector-country input[type="hidden"]').val(), firstResponse);
						var countryVal = countryValInput.val();
						if ($('#' + countryVal).length <= 0) {
							var nocache = '';
							if (location.href.match(/nocache=/i)) {
								nocache = '&nocache=1';
							}
							var cityLetter = '',
								currentCity = $('#city-selector .custom-select-header span'),
								currentCityText = $.trim(currentCity.text())
							;
							if (!currentCity.parent(0).hasClass('disabled') && currentCityText != currentCity.metadata().defText) {
								cityLetter = "&cityLetter=" + currentCityText.substring(0,1);
							}
							$.ajax({
								url: "/a_ajax/location.getCitiesData?id=" + countryValInput.val() + cityLetter + nocache,
								type     : "GET",
								dataType : "json",
								timeout: 10000,
								success: firstResponse,
								error: firstRequestError
							});
						} else {
							citySetContentFromHTML();
						}
					}, 1000);
				}
				bodyUnbindClick();
				$(elm).parents('.custom-select').find('.custom-select-header div').addClass('sel-active');
				
				var subActiveLinkActive = $(elm).parents('.custom-select').find('div.custom-select-body-i .subActive .active');
				if (subActiveLinkActive.length > 0) {
					
					subActiveLinkActive.parents('.subActive').show().prev(0).find('td.hasSub').addClass('hasSubActive');
				}
				if (!$.browser.msie) {
					$(elm).parents('.custom-select').find('.custom-select-body').slideDown('fast', function() {
						setTimeout(bodyClickCSelectHide, 500);
						scrollBody($(elm));
					});
				} else {
					$(elm).parents('.custom-select').find('.custom-select-body').show();
					scrollBody($(elm));
				}
			}
		};
		var hideCustomSelect = function(elm) {
			$(elm).parents('.custom-select').find('.custom-select-header div').removeClass('sel-active');
			hideThis($(elm).parents('.custom-select').find('.custom-select-body'));
			showCustomSelectVar = false;
		};
		var firstResponse = function(data) {
			if (data) {
				if (data.cities != undefined || data.cities.length > 0) {
					firstCitiesData = data;
					$('#ajax-loader').remove();
					if (countryValInput.val() != '') {
						countrySelectorEnable();
						citySelectorEnable();
						citySelectorRemoveWait();
					} else {
						//alert('ERROR'.translate());
					}
					linksArray = [];
					for (var ii = 0; ii < data.links.length; ii++) {
						linksArray.push(data.links[ii].url);
					}
					var links = data.links;
					
					responseEval(data, 0, undefined);
					
//					var blockContainersCount = $('#city-selector .custom-select-body-i tr.c-navigation').size();
					for (var t = 0; t < links.length; t++) {
//						var letter = (links[t].first != links[t].last) ? (links[t].first + ' - ' + links[t].last) : links[t].first;
						var letter = links[t].caption;
						$('#city-selector .custom-select-body-i > table').append('<tbody class="c-navigation-body"><tr class="c-navigation"><td colspan="4"><a href="javascript:void(0)" class="{linkNum: ' + (t + 1) + ', first: \'' + links[t].first + '\', last: \'' + links[t].last +'\', url: \'' + links[t].url + '\'}">' + letter + '</a></td></tr></tbody>');
					}

					$('#city-end-selector .custom-select-body-i table').html($('#city-selector .custom-select-body-i table').html());

					selectCityBind(data.cities);
					//$('#city-selector .custom-select-body .cities-block td').not('.hasSub').find('a, #city-end-selector .custom-select-body .cities-block a').unbind('mousedown').bind('mousedown', {locations: data.cities}, selectCity);
					
					$('#city-selector .custom-select-body-i .c-navigation a').unbind('mousedown').bind('mousedown', lettersCoose);
					$('#city-end-selector .custom-select-body-i .c-navigation a').unbind('mousedown').bind('mousedown', lettersCooseCityEnd);
					
					if ($('#' + countryValInput.val()).length <= 0) {
						$('body').append('<div id="' + countryValInput.val() + '" style="display:none;"></div>');
						countriesArray[countryValInput.val()] = data;
					}
					
					var citySpan = $('#city-selector .custom-select-header span');
					if (data.opened.length > 0 && $.trim(citySpan.text()).toLowerCase() != citySpan.metadata().defText.toLowerCase() && !citySpan.parent(0).hasClass('disabled')) {
						nextResponse(data.opened[0]);
						scrollBody(citySpan);
					}
					
					//$('#city-selector .custom-select-body-i')
				} else {
					span.find('span').text('NO_CITY'.translate());
					citySelectorDisable();
					citySelectorRemoveWait();
				}
				citySelHeightIE();
			} else {
				span.hide();
				$('#city-selector .custom-select-header').append('<strong class="ct-error">' + 'ERROR'.translate() + '</strong>');
			}
		};
		var responseEval = function(data, clickedNum, tBody) {
			dataOld = data;
			data = data.cities;
			var currentLetter = '';
			var blockSize = 0;
			var oneLetterCities = [];
			var colsCount = 4;
			var container = $('#city-selector .custom-select-body-i > table');
			var putCitiesInBlock = function(oneLetterCities, currentLetter) {
				if (oneLetterCities.length > 0) {
					if(currentLetter != '') {
						if (clickedNum > 0 && tBody != undefined) {
							tBody.append('<tr class="letter"><th colspan="4">' + currentLetter + '</th></tr>');
						} else {
							container.append('<tr class="letter"><th colspan="4">' + currentLetter + '</th></tr>');
						}
					}
					var blocksize = Math.ceil(oneLetterCities.length/colsCount);
					
					var setSubCities = function(subCities, trR, num) {
						var trAfter = $('<tr class="subActive subActive_' + num + '"></tr>');
						trAfter.append('<td colspan="4"><div class="subDiv"><table></table></div></td>');
						var blocksize = Math.ceil(subCities.length/colsCount);
						var container = trAfter.find('table');
						for (var a = 0; a < blocksize; a++) {
							var tr = $('<tr class="cities-block"></tr>');
							for (b = a; b < subCities.length; b += blocksize) {
								var city = subCities[b];
								if (city == undefined) {
									break;
								}
								var selectedCity = '';
								if (city.t.toLowerCase() == $('#city-selector .custom-select-header span').text().toLowerCase().replace(/(^\s+)|(\s+$)/g, "")) {
									selectedCity = ' class="active"';
								}
								var created = (city.r != undefined && city.r == 1 && false);
								insertedTd = $('<td' + selectedCity + '><a href="javascript:void(0)" name="' + city.n + '" title="' + city.t + '">' + (created ? '<b>' : '') + city.t + (created ? '</b>' : '') + '</a></td>');
								tr.append(insertedTd);
							}
							container.append(tr);
						}
						if (trR.next(0).hasClass('subActive')) {
							if (trR.next(1).hasClass('subActive')) {
								if (trR.next(2).hasClass('subActive')) {
									trR.next(2).after(trAfter);
								} else {
									trR.next(1).after(trAfter);
								}
							} else {
								trR.next(0).after(trAfter);
							}
						} else {
							trR.after(trAfter);
						}
					};
					
					for (var a = 0; a < blocksize; a++) {
						var tr = $('<tr class="cities-block"></tr>');
						var newCityN = '';
						var subcitiesArray = [];
						for (b = a; b < oneLetterCities.length; b += blocksize) {
							var city = oneLetterCities[b];
							if (city == undefined) {
								break;
							}
							var selectedCity = '';
							if (city.t.toLowerCase() == $('#city-selector .custom-select-header span').text().toLowerCase().replace(/(^\s+)|(\s+$)/g, "")) {
								selectedCity = 'active ';
							}
							var created = (city.r != undefined && city.r == 1 && false);
							var class_hasSub = '';
							var moreLink = '';
							if (firstCitiesData.subcities != undefined && firstCitiesData.subcities[city.n] != undefined) {
								newCityN = city.n;
								class_hasSub = 'hasSub';
								subCities = firstCitiesData.subcities[city.n];
								moreLink = '<strong>&darr;</strong> ';
							}
							var insertedTd = $('<td class="' + selectedCity + class_hasSub +'">' + moreLink + '<a href="javascript:void(0)" name="' + city.n + '" title="' + city.t + '">' + (created ? '<b>' : '') + city.t + (created ? '</b>' : '') + '</a>' + '</td>');
							tr.append(insertedTd);
							if (insertedTd.hasClass('hasSub')) {
								insertedTd.attr('name', insertedTd.prevAll('td.hasSub').length+1);
							}
						}
						if (clickedNum > 0 && tBody != undefined) {
							tBody.append(tr);
						} else {
							container.append(tr);
						}
						if (firstCitiesData.subcities != undefined && firstCitiesData.subcities[newCityN] != undefined) {
							tr.find('td.hasSub').each(function() {
								setSubCities(firstCitiesData.subcities[$(this).find('a').attr('name')], tr, parseInt($(this).attr('name')));
							});
						}
					}
					
					oneLetterCities = [];
				}
				return oneLetterCities;
			};
			
			if (clickedNum == 0 && dataOld.rated.length > 0) {
				var rCities = [];
				for (var h = 0; h < dataOld.rated.length; h++) {
					rCities.push(dataOld.rated[h]);
				}
				putCitiesInBlock(rCities, '<span>' + 'MOST_POPULAR_CITIES'.translate() + '</span>');
			}
			
			for (var i = 0; i < data.length; i++) {
				var newLetter = data[i].t.substr(0, 1).toUpperCase();
				if (i == 0 && clickedNum == 0) {
					container.find('tbody:first tr.cities-block a').addClass('popular');
				}
				if (currentLetter != newLetter) {
					oneLetterCities = putCitiesInBlock(oneLetterCities, currentLetter);
					currentLetter = newLetter;
				}
				oneLetterCities.push(data[i]);
			}
			
			oneLetterCities = putCitiesInBlock(oneLetterCities, currentLetter);

			if (tBody != undefined) {
				$('#city-selector div.custom-select-body').scrollTo($(tBody), 800, {offset:-80});
			}
			//$('#city-selector div.custom-select-body-i .num-container:first').css({paddingBottom: '0', marginBottom: '0'});
//			$('#city-selector div.custom-select-body-i .c-navigation:last').css({marginBottom: '0'});

			
		};
		var responseEvalCityEnd = function(data, clickedNum) {
			data = data.cities;
			var currentLetter = '';
			var blockSize = 0;
			var oneLetterCities = [];
			var colsCount = 4;
			var container = $('#city-end-selector .custom-select-body-i');
//			var blockContainer = $('<div class="num-container {num:' + clickedNum + '}"></div>');
			/*if(clickedNum == 0)	{
				container.append(blockContainer);
			} else {
				var insertAfter = $('#city-end-selector .custom-select-body-i div').filter(function() {
					var v = $(this).metadata().num;
					return (v != undefined && v == clickedNum);
				});
				blockContainer.insertAfter(insertAfter);
				container.children('div:last').css({marginBottom: 0, paddingBottom: 0});
			}*/
			var putCitiesInBlock = function(oneLetterCities, currentLetter) {
				if (oneLetterCities.length > 0) {
					if(currentLetter != '') {
						blockContainer.append('<div class="cities-block clear-after"><div class="letter">' + currentLetter + '</div></div>');
					}
					var blocksize = Math.floor(oneLetterCities.length/colsCount);
					var blocksizeRest = oneLetterCities.length - colsCount * blocksize;
					var iter = 0;
					for (var j = 0; j < colsCount; j++) {
						var ul = $('<div class="ul"></div>');
						var blockSizeIter = blocksize;
						if(blocksizeRest > 0) {
							--blocksizeRest;
							blockSizeIter++;
						}
						for (var k = 0; k < blockSizeIter; k++) {
							var city = oneLetterCities[iter++];
							if (city == undefined) {
								break;
							}
							var selectedCity = '';
							if (city.t.toLowerCase() == $('#city-end-selector .custom-select-header span').text().toLowerCase().replace(/(^\s+)|(\s+$)/g, "")) {
								selectedCity = ' class="active"';
							}
							var created = (city.r != undefined && city.r == 1);
							ul.append('<a' + selectedCity + ' href="javascript:void(0)" class="' + (city.l != undefined ? 'has_regions' : '') + '" name="' + city.n + '" title="' + city.t + '">' + (created ? '<b>' : '') + city.t + (created ? '</b>' : '') + '</a>');
						}
						blockContainer.find('.cities-block:last').append(ul);
					}
					oneLetterCities = [];
				}
				return oneLetterCities;
			};
			if (clickedNum == 0 && dataOld.rated.length > 0) {
				var rCities = [];
				for (var h = 0; h < dataOld.rated.length; h++) {
					rCities.push(dataOld.rated[h]);
				}
				putCitiesInBlock(rCities, '<span>' + 'MOST_POPULAR_CITIES'.translate() + '</span>');
			}
			for (var i = 0; i < data.length; i++) {
				var newLetter = data[i].t.substr(0, 1).toUpperCase();
				if (currentLetter != newLetter) {
					oneLetterCities = putCitiesInBlock(oneLetterCities, currentLetter);
					currentLetter = newLetter;
				}
				oneLetterCities.push(data[i]);
			}
			oneLetterCities = putCitiesInBlock(oneLetterCities, currentLetter);
			$('#city-end-selector div.custom-select-body').scrollTo(blockContainer, 800, {offset:-80});
			$('#city-end-selector div.custom-select-body-i .c-navigation:last').css({marginBottom: '0'});
		};
		var lettersCoose = function() {
			var $this = $(this);
			$.getJSON(linksArray[$this.metadata().linkNum - 1], nextResponse);
			lettersCooseWait(true);
		};
		var lettersCooseCityEnd = function() {
			var $this = $(this);
			$.getJSON(linksArray[$this.metadata().linkNum - 1], nextResponseCityEnd);
			lettersCooseWait(true);
		};
		var lettersCooseWait = function(bool) {
			var csb = $('#city-selector div.custom-select-body-i, #city-end-selector div.custom-select-body-i');
			if (bool) {
				csb.css({opacity: '0.3'});
				csb.find('a').attr('disabled', 'disabled');
			} else {
				csb.css({opacity: '1'});
				csb.find('a').removeAttr('disabled');
			}
		};
		var nextResponse = function(data) {
			citySelHeightIE();
			lettersCooseWait(false);
			var link = $('#city-selector .custom-select-body-i .c-navigation a').filter(function(i){
				var v = $(this).metadata().first;
				return (v != undefined && v == data.first);
			});
			var clickedNum = link.metadata().linkNum;
			responseEval(data, clickedNum, link.parents('tbody.c-navigation-body'));
			link.parents('tr.c-navigation').remove();
			//var nc = $('#city-selector div.custom-select-body-i .num-container');
			selectCityBind();
		};
		var nextResponseCityEnd = function(data) {
			citySelHeightIE();
			lettersCooseWait(false);
			var link = $('#city-end-selector .custom-select-body-i .c-navigation a').filter(function(i){
				var v = $(this).metadata().first;
				return (v != undefined && v == data.first);
			});
			var clickedNum = link.metadata().linkNum;
			responseEvalCityEnd(data, clickedNum);
			link.parents('tr.c-navigation').remove();
			selectCityBind();
		};

		if (undefined !== window.citiesJSON && null !== window.citiesJSON && typeof(citiesJSON) == 'object' && window.citiesJSON.cities.length > 0) {
			firstResponse(citiesJSON);
		}
		
		// Customizise all selects in the search form
		var cSelectClick = function() {
			var $this = $(this);
			var sBody = $this.next('.simple-select');
			$('.custom-select .custom-select-header div').removeClass('sel-active');
			if (sBody.is(':hidden')) {
				$('.custom-select .custom-select-body').not(this).hide();
				bodyUnbindClick();
				//$this.find('div').css({backgroundPosition: '100% 0', borderColor: '#D6C6BB'});
				$this.find('div').addClass('sel-active');
				if (!$.browser.msie) {
					$('.custom-select .custom-select-body').slideUp('fast');
					sBody.slideDown(function() {
						bodyClickCSelectHide();
						if ($this.find('span').text().replace(/(^\s+)|(\s+$)/g, "") != $this.find('span').metadata().defText && $this.attr('id') == 'selector-country') {
							sBody.scrollTo(sBody.find('.active'), 100, {offset: -20});
						}
						//sBody.scrollTo(sBody.find('.active'), 100, {offset: -20});
					});
				} else {
					$('.custom-select .custom-select-body').hide();
					sBody.show();
					if ($this.find('span').text().replace(/(^\s+)|(\s+$)/g, "") != $this.find('span').metadata().defText && $this.attr('id') == 'selector-country') {
						sBody.scrollTo(sBody.find('.active'), 100, {offset: -20});
					}
				}
			} else {
				$this.find('div').removeClass('sel-active');
				hideThis(sBody);
			}
			var tw = $this.width();
			var sbw = sBody.width();
			if (sbw < tw) {
				sBody.width(tw);
			} else {
				sBody.width(sbw);
			}
			sBody.find('ul a').unbind('');
			if ($this.parents('.custom-select').attr('id') != 'selector-country') {
				sBody.find('ul a').mousedown(function() {
					var aClicked = $(this);
					var aClickedText = aClicked.text().replace(/(^\s+)|(\s+$)/g, '');
					var newVal = (aClicked.metadata().value != undefined) ? aClicked.metadata().value : '';
					aClicked.parents('.custom-select').find('input[type="hidden"]').val(newVal);
					aClicked.parents('.custom-select').find('.custom-select-header span').text(aClickedText);
					aClicked.parent().parent().find('li').removeClass('active');
					aClicked.parent(0).addClass('active');
					hideThis(aClicked.parents('.simple-select'));
					$this.find('div').removeClass('sel-active');
				});
			}
			
			//$this.next('.simple-select').scrollTo($this.next('.simple-select').find('ul li.active'), 100, {queue:true});
		};
		$('.custom-select').not('#city-selector').find('.custom-select-header').bind('mousedown', cSelectClick);
		
		/*if (supplier.find('input[type="hidden"]').val() == 0) {
			companySelectorDisable();
		}*/

		var showPassengerAges = function(val, clicked) {
			var aVal;
			aVal = clicked ? $(val).metadata().value : $(val).metadata().value;
			var chlist = $('#adults-list');
			var isAir = false;
			if ($(val).parents('form').attr('id') == 'frm-air') {
				isAir = true;
			}
			$('#adults-list>li').hide();
			if (aVal > 0) {
				if (isAir) {
					$('.extended-search').show();
				} else {
					chlist.show();
					$('.hotel_search_more').show();
				}
				$('.more-less-controls a.more').hide();
				$('.more-less-controls a.less').css('display', 'block');
			} else {
				chlist.hide();
				$('.hotel_search_more .extended-search').hide();
				$('.more-less-controls a.more').css('display', 'block');
				$('.more-less-controls a.less').hide();
			}
			if (clicked) {
				$('#adults-list li input[type="hidden"]').remove();
			}
			for (var i = 1; i <= aVal; i++) {
				var iChild = '#adults-list li:nth-child(' + i + ')';
				if (isAir == false) {
					$(iChild + ' label').text(ordinals[i-1] + ' ' + 'TOURIST'.translate() + ':');
				}
				$(iChild).css('display', 'block');
				if (clicked && !$('#adults-list li:nth-child(' + i + ') input[type="hidden"]').length > 0) {
					var t = $(iChild + ' .custom-select-header div span');
					var n = t.metadata().defVal;
					$(iChild + ' .custom-select').prepend('<input class="js-added" type="hidden" name="p[]" value="' + n + '" />');
					$(iChild + ' .custom-select .custom-select-body-i li').removeClass('active');
					$(iChild + ' .custom-select .custom-select-body-i li:first').addClass('active');
					t.text($(iChild + ' .custom-select .custom-select-body-i li:first a').text());
				}
			}
		};
		/*
		if ($('#tourists-number').val() > 0) {
			showPassengerAges($('#tourists-number').val(), false);
		}
		*/

		$('#adults .custom-select-body-i ul li a').bind('mousedown', function() {showPassengerAges(this, true);});

		$('#frm-hotel-search').submit(frmSubmit);

		function frmSubmit() {
			var arrName = [], arrVal = [];
			$('#frm-hotel-search input[type="text"], #frm-hotel-search input[type="hidden"]').each(function() {
				if ($(this).attr('name') != undefined && $(this).val() != undefined) {
					arrName.push($(this).attr('name'));
					arrVal.push($(this).val());
				}
			});
			$('#frm-hotel-search input[type="checkbox"]').each(function() {
				if ($(this).attr('checked') == true) {
					arrName.push($(this).attr('name'));
					arrVal.push($(this).val());
				}
			});
			var u = '';
			u += arrName[0] + '=' + arrVal[0];
			for (var i = 1; i < arrName.length; i++) {
				u += '&' + arrName[i] + '=' + arrVal[i];
			}
			var e = document.domain + '' + $(this).attr('action');
			setTimeout(function() {searchWaitRedirect(e, u);}, tm.Config.searchResultsTimeout);
		}
		function searchWaitRedirect(e, u) {
			var domain = e + '?' + u;
			window.location = 'http://' + domain;
		}

    });
})(jQuery);